<template>
  <div class="password-container">
    <div class="password-card">
      <div class="card-header">
        <el-icon class="header-icon"><Lock /></el-icon>
        <h2 class="password-title">修改密码</h2>
        <p class="password-subtitle">为了保障账号安全，请设置符合要求的密码</p>
      </div>

      <el-form
          ref="formRef"
          :model="data.user"
          :rules="rules"
          label-width="120px"
          class="password-form"
      >
        <el-form-item label="原密码" prop="password">
          <el-input
              v-model="data.user.oldPassword"
              show-password
              class="custom-input"
              :prefix-icon="Lock"
              placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="data.user.newPassword"
              show-password
              class="custom-input"
              :prefix-icon="Lock"
              placeholder="请输入8-20位新密码"
          />
          <div class="password-strength" v-if="data.user.newPassword">
            <div class="strength-label">密码强度:</div>
            <div class="strength-bars">
              <span :class="['bar', getStrengthClass(passwordStrength)]"></span>
              <span :class="['bar', getStrengthClass(passwordStrength, 2)]"></span>
              <span :class="['bar', getStrengthClass(passwordStrength, 3)]"></span>
            </div>
            <span class="strength-text">{{ strengthText }}</span>
          </div>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              v-model="data.user.confirmPassword"
              show-password
              class="custom-input"
              :prefix-icon="Lock"
              placeholder="请再次输入新密码"
          />
        </el-form-item>

        <div class="password-tips">
          <el-icon><InfoFilled /></el-icon>
          <span>密码要求：</span>
          <ul>
            <li>长度为8-20个字符</li>
            <li>必须包含字母和数字</li>
            <li>建议包含特殊字符</li>
          </ul>
        </div>

        <div class="button-section">
          <el-button @click="resetForm" class="reset-button">
            重置
          </el-button>
          <el-button type="primary" @click="submitForm" class="save-button" :loading="loading">
            <el-icon class="save-icon"><Key /></el-icon>
            确认修改
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from "vue"
import { Lock, Key, InfoFilled } from '@element-plus/icons-vue'
import request from "@/utils/request"
import { ElMessage } from "element-plus"
import router from "@/router"
import {getUserInfo} from "@/utils/auth";

const formRef = ref(null)
const loading = ref(false)

const data = reactive({
  user: {
    userId: getUserInfo()?.id || {},
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
})

onMounted(() => {
  data.user.oldPassword = ''
})

// 表单验证规则
const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在8-20个字符之间', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,20}$/,
      message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 密码强度计算
const passwordStrength = computed(() => {
  const password = data.user.newPassword || ''
  let strength = 0

  if (password.length >= 8) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/[a-z]/.test(password)) strength++
  if (/[0-9]/.test(password)) strength++
  if (/[^A-Za-z0-9]/.test(password)) strength++

  return Math.min(strength, 3)
})

const strengthText = computed(() => {
  const texts = ['弱', '中', '强']
  return texts[passwordStrength.value - 1] || ''
})

// 确认密码验证
function validateConfirmPassword(rule, value, callback) {
  if (value !== data.user.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      request.put('/sysUser/updatePassword', data.user).then(res => {
        loading.value = false
        if (res.code === '200') {
          ElMessage.success('密码修改成功，请重新登录')
          localStorage.removeItem('system-user')
          router.push('/login')
        } else {
          ElMessage.error(res.msg || '修改失败')
        }
      }).catch(() => {
        loading.value = false
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
}

// 获取密码强度样式
const getStrengthClass = (strength, level = 1) => {
  return {
    'strength-weak': strength >= level && strength === 1,
    'strength-medium': strength >= level && strength === 2,
    'strength-strong': strength >= level && strength === 3,
    'strength-empty': strength < level
  }
}
</script>

<style scoped>
.password-container {
  width: 50%;
  min-width: 320px;
  margin: 40px auto;
}

.password-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.card-header {
  text-align: center;
  margin-bottom: 40px;
}

.header-icon {
  font-size: 48px;
  color: #c8161d;
  margin-bottom: 16px;
}

.password-title {
  color: #333;
  font-size: 28px;
  margin-bottom: 12px;
  font-weight: 600;
}

.password-subtitle {
  color: #666;
  font-size: 14px;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-label {
  font-size: 12px;
  color: #666;
}

.strength-bars {
  display: flex;
  gap: 4px;
}

.bar {
  width: 30px;
  height: 4px;
  border-radius: 2px;
  background: #eee;
  transition: all 0.3s;
}

.strength-weak { background: #ff4d4f; }
.strength-medium { background: #faad14; }
.strength-strong { background: #52c41a; }
.strength-empty { background: #eee; }

.strength-text {
  font-size: 12px;
  color: #666;
}

.password-tips {
  margin: 24px 0;
  padding: 16px;
  background: #f8f8f8;
  border-radius: 8px;
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.password-tips ul {
  margin: 0;
  padding-left: 20px;
}

.password-tips li {
  margin: 4px 0;
}

.button-section {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 40px;
}

.reset-button,
.save-button {
  min-width: 120px;
  height: 40px;
  border-radius: 8px;
  font-size: 14px;
}

.save-button {
  background: linear-gradient(90deg, #c8161d, #e54b4b);
  border: none;
}

.save-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(200, 22, 29, 0.3);
}

/* 响应式适配 */
@media screen and (max-width: 768px) {
  .password-container {
    width: 90%;
    margin: 20px auto;
  }

  .password-card {
    padding: 24px;
  }

  .password-title {
    font-size: 24px;
  }

  .button-section {
    flex-direction: column;
  }

  .reset-button,
  .save-button {
    width: 100%;
  }
}
</style>
